package com.wangjw.seckill.controller;

import com.wangjw.seckill.domain.User;
import com.wangjw.seckill.redis.RedisService;
import com.wangjw.seckill.redis.UserKey;
import com.wangjw.seckill.result.CodeMsg;
import com.wangjw.seckill.result.Result;
import com.wangjw.seckill.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by wangjw on 18/1/5.
 */
@Controller
@RequestMapping("/demo")
public class SampleController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisService redisService;

    @RequestMapping("/hello")
    public String thymeleaf(Model model) {
        model.addAttribute("name", "wangjw");
        return "hello";
    }

    @RequestMapping("/hello-success")
    @ResponseBody
    public Result<String> helloSuccess() {
        return Result.success("hello seckill2");
    }

    @RequestMapping("/hello-error")
    @ResponseBody
    public Result<String> helloError() {
        return Result.error(CodeMsg.SERVER_ERROR);
    }

    @RequestMapping("/db/get")
    @ResponseBody
    public Result<User> dbGet() {
        User user = userService.getById(1002);
        return Result.success(user);
    }

    @RequestMapping("/db/tx")
    @ResponseBody
    public Result<Boolean> tx() {
        return Result.success(userService.tx());
    }

    @RequestMapping("/redis/get")
    @ResponseBody
    public Result<User> redisGet() {
        User user = redisService.get(UserKey.getById, "" + 1004, User.class);
        return Result.success(user);
    }

    @RequestMapping("/redis/set")
    @ResponseBody
    public Result<Boolean> redisSet() {
        User user = new User(1004, "njj");
        boolean ret = redisService.set(UserKey.getById, "" + 1004, user); //"UserKey:id1004"
        return Result.success(ret);
    }
}
